/**
 * Created by kevin on 2017/5/31.
 */
var express = require('express');
var router = express.Router();

var Users = require('../models/Users');
var Robots = require('../models/Robots');
var Applications = require('../models/Applications');
var Packages = require('../models/Packages');

var ucheck = require('../utils/ucheck');
var events = require('events');

var Delegaters = require('../models/Delegaters');

var scripter = require('../utils/scripter');

var stream = require('../utils/stream');
var fs = require("fs");
var push = require('../utils/push');
let archiveTool = require('../utils/archive');
var versionC = require('../utils/version');
// var webinfo = require('../config/website.conf.json');
let webinfo = require('../utils/website');

var dingding = require('../utils/dingding');
var multer  = require('multer');
var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        let name = file.originalname;
        if (name.slice(-3) === 'ipa') {
            cb(null, 'data/Packages/iOS/')
        } else  if  (name.slice(-3) === 'apk') {
            cb(null, 'data/Packages/Android/')
        }
    },
    //给上传文件重命名，获取添加后缀名
    filename: function (req, file, cb) {
        cb(null, file.originalname);
    }
});
let Docs = require('../models/Docs');
let DocClassifies = require('../models/DocClassifies');
var upload = multer({storage:storage});

router.post('/upload', upload.single('package'),function (req,res,next) {
    var file = req.file;
    if (file.originalname.indexOf('.ipa') < 0 && file.originalname.indexOf('.apk') < 0) {
        return res.json({
            message : '类型不匹配',
            code : -1,
            data : null
        });
    }
    var id = req.body['package_id'];
    if (!id) {
        return res.json({
            message : 'package_id不能为空',
            code : -1,
            data : null
        });
    }
    Packages.getById(id,function (err,package) {
        if (err) {
            return res.json({
                message : err.message,
                code : -1,
                data : null
            });
        }
        if (!package) {
            return res.json({
                message : 'package不存在',
                code : -1,
                data : null
            });
        }
        var path = '';
        var bundleId = package.app.bundleId;
        var version = package.version;
        var build = package.build;
        if (package.type === 1) {
            path = file.path;
            var pathComs = path.split('.ipa');
            path = pathComs[0] + '.plist';
            var appName = package.app.name;
            var content = `<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>items</key>
    <array>
        <dict>
            <key>assets</key>
            <array>
                <dict>
                    <key>kind</key>
                    <string>software-package</string>
                    <key>url</key>
                    <string>${webinfo.url}/data/Packages/iOS/${bundleId}-${version}-${build}.ipa</string>
                </dict>
            </array>
            <key>metadata</key>
            <dict>
                <key>bundle-identifier</key>
                <string>${bundleId}</string>
                <key>bundle-version</key>
                <string>${version}</string>
                <key>kind</key>
                <string>software</string>
                <key>title</key>
                <string>${appName}</string>
            </dict>
        </dict>
    </array>
</dict>
</plist>`;
            fs.writeFileSync(path,content,'utf8');
        } else if (package.type === 2) {
            path = `data/Packages/Android/${bundleId}-${version}-${build}.apk`;
        }

        Packages.edit(id,{dlurl : webinfo.url(req) + '/' + path},function (err,data) {
            if (err) {
                return res.json({
                    message : err.message,
                    code : -1,
                    data : null
                });
            } else  {
                return res.json({
                    message : '上传成功',
                    code : 0,
                    data : null
                });
            }
        });
    });
    // [{"fieldname":"package","originalname":"1.ipa","encoding":"7bit","mimetype":"application/octet-stream","destination":"data/Packages/iOS/","filename":"1.ipa","path":"data/Packages/iOS/1.ipa","size":14450813}]
});

router.get('/download/:id',function (req,res) {
    var id = req.params.id;
    Packages.getById(id,function (err,data) {
        if (err || !data) {
            req.flash('error', '包信息不合法');
            res.redirect('/');
            return;
        }
        res.render('package/download',{title:data.app.name+'安装',package:data,layout:null,host:webinfo.url(req),url:'/package/download/'+id});
    });
});

router.get('/archive/:id',function (req,res) {
    var id = req.params.id;
    Applications.getById(id, function (err,app) {
        if (err) {
            res.json({
                message : err.message,
                code : -1,
                data : null
            });
        } else {
            if (app) {
                if (app.status === 1) {
                    res.render('user/debug',{layout:'layout1.ejs',title:'正在打包'+app.name,action:'archive',tag:app.name});
                } else {
                    res.json({
                        message : app.name + '并未在打包过程中',
                        code : -1,
                        data : null
                    });
                }
            } else {
                res.json({
                    message : '系统异常',
                    code : -1,
                    data : null
                });
            }

        }
    });
});

router.get('/log/:id',function (req,res) {
    var id = req.params.id;
    Packages.getById(id,function (err,data) {
        if (err) {
            return res.json({
                message : err.message,
                code : -1,
                data : null
            });
        }
        if (data.status === 1) {
            res.redirect('/package/download/'+id);
        } else if (data.status === 0) {
            res.redirect('/package/archive/'+data.app._id);
        } else if (data.status === -1) {
            var address = 'data/log/packages/' + (data.type === 1 ? 'ios/' : 'android/') + data.app.bundleId + "_" + data.version + '_' + data.build + '.log';
            var file = fs.createReadStream(address,{
                encoding : 'utf-8',
                autoClose: true
            });
            var content = '';
            var error = null;
            file.on("open", function(fd) {
                content = '<p>';
            });
            file.on("data", function(data) {
                content += (data.replace(/\n/g,'</p><p>'));
                // res.send(data+'\n');
            });
            file.on("end", function() {

            });
            file.on("close", function() {
                if (error) {
                    return res.json({
                        message : err.message,
                        code : -1,
                        data : null
                    });
                } else {
                    content += '</p>';
                    res.send(content);
                }
            });
            file.on("error", function(err) {
                error = err;

            })
        }
    })
});

router.get('/*',function (req,res,next) {
    ucheck.hasLogin(res,function (has) {
        if (!has) {
            req.flash('error', '请先登录');
            res.redirect('/user/login?redirect='+req.originalUrl);
            return;
        }
        ucheck.AIPackager(res,function (is) {
            if (!is) {
                req.flash('error', '您无权查看');
                return res.redirect('/');
            }
            next();
        });
    });
});

router.post('/*',function (req,res,next) {
    let apiToken = req.body.apiToken;
    if (apiToken) {
        return next();
    }
    ucheck.hasLogin(res,function (has) {
        if (!has) {
            return res.json({
                message : '请先登录',
                code : -1,
                data : null
            });
        }
        ucheck.AIPackager(res,function (is) {
            if (!is) {
                return res.json({
                    message : '您无权查看',
                    code : -1,
                    data : null
                });
            }
            next();
        });
    });
});

router.get('/', function(req, res, next) {
    let platform = req.query.platform;
    let appId = req.query.app_id;
    if (platform && platform.length > 0) {
        platform = platform.toLowerCase();
    } else  {
        platform = 'ios';
    }
    var role = res.locals.user.role;
    if (platform === 'android' && ucheck.canPackageAndroidSync(res)) {
        // 安卓
        req.session.addType = 2;
        Robots.getAll(function (err,robots) {
            Applications.getListByType(req.session.addType,function (err,apps) {
                res.render('package/list',{title:'Android打包服务',type:2,platform:'Android',robots:robots,apps:apps,appId:appId ? appId : null});
            });
        })

    } else if (platform === 'ios' && ucheck.canPackageIOSSync(res)) {
        // ios
        req.session.addType = 1;
        Robots.getAll(function (err,robots) {
            Applications.getListByType(req.session.addType,function (err,apps) {
                res.render('package/list',{title:'iOS打包服务',type:1,platform:'iOS',robots:robots,apps:apps,appId:appId ? appId : null});
            });
        })
    } else if (platform !== 'android' && platform !== 'ios') {
        // 非法
        req.flash('error', '平台信息有误，请核实');
        res.redirect('/');
    } else {
        req.flash('error', '您无权查看');
        res.redirect('/');
    }
});

router.post('/list',function (req,res) {
    var page = req.body['page'];
    var id = req.body['id'];
    Packages.getCountByAppId(id,function (e,count) {
        Packages.getPartByAppId(id,(page - 1) * 10,10,function (err,packages) {
            if (err) {
                res.json({
                    message : err.message,
                    code : -1,
                    data : null
                });
            } else  {
                res.json({
                    message : '成功',
                    code : 0,
                    data : {
                        list:packages,
                        page:page,
                        pagesize:10,
                        total:count || 0
                    }
                });
            }
        });
    });
});

router.post('/delete',function (req,res) {
    var ids = req.body['ids'];
    var idList = JSON.parse(ids);

    Packages.getByIds(idList,function (err,packages) {
        if (err) {
            res.json({
                message : err.message,
                code : -1,
                data : null
            });
        } else {
            for (var data of packages) {
                if (data) {
                    var address = 'data/log/packages/' + (data.type === 1 ? 'ios/' : 'android/') + data.app.bundleId + "_" + data.version + '_' + data.build + '.log';
                    if (fs.existsSync(address)) {
                        fs.unlinkSync(address);
                    }
                    var path = 'data/Packages/' + (data.type === 1 ? 'iOS/' : 'Android/') + data.app.bundleId + '-' + data.version + '-' + data.build;
                    var plist = path + '.plist';
                    var ipa = path + '.ipa';
                    if (fs.existsSync(plist)) {
                        fs.unlinkSync(plist);
                    }
                    if (fs.existsSync(ipa)) {
                        fs.unlinkSync(ipa);
                    }
                }
            }
            Packages.remove({_id:{
                $in : idList,
            }},function (err,data) {
                if (err) {
                    res.json({
                        message : err.message,
                        code : -1,
                        data : null
                    });
                } else {
                    res.json({
                        message : '成功',
                        code : 0,
                        data : null
                    });
                }
            });
        }

    });
});

router.post('/delegater/list',function (req,res) {
    Delegaters.getListByType(req.session.addType,function (err,delegaters) {
        if (err) {
            res.json({
                message : err.message,
                code : -1,
                data : null
            });
        } else  {
            res.json({
                message : '成功',
                code : 0,
                data : delegaters
            });
        }

    })
});

router.post('/archive/ios',function (req,res) {

    let uid = res.locals.user._id;
    let appId = req.body['app_id'];
    let delId = req.body['del_id'];

    console.log('打包了');
    archiveTool.archiveIOS(req,uid,appId,delId,req.session.socketServer,function (err,data) {
        if (err) {
            res.json({
                code : -1,
                message : err.message,
                data : null
            });
        } else {
            res.json({
                code : 0,
                message : '成功',
                data : data
            })
        }
    });


});

router.post('/archive/android',function (req,res) {
    var uid = res.locals.user._id;
    var appId = req.body['app_id'];
    var delId = req.body['del_id'];

    archiveTool.archiveAndroid(req,uid,appId,delId,req.session.socketServer,function (err,data) {
        if (err) {
            res.json({
                code : -1,
                message : err.message,
                data : null
            });
        } else {
            res.json({
                code : 0,
                message : '成功',
                data : data
            })
        }
    });

});

module.exports = router;
